<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="资产设备名称" prop="assetName">
        <el-select
          v-model="queryParams.assetName"
          placeholder="请选择资产设备名称"
          clearable
          @change="handleQuery"
          style="width: 220px;"
        >
          <el-option
            v-for="(name, index) in uniqueAssetNames"
            :key="`${name}-${index}`"
            :label="name"
            :value="name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="移动时间范围">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          style="width: 320px;"
          @clear="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equ:scrap:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equ:scrap:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equ:scrap:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equ:scrap:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="scrapList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="报废申请id" align="center" prop="scrapId" />
      <el-table-column label="资产设备名称" align="center" prop="assetName"/>
      <el-table-column label="正式报废日期" align="center" prop="scrapDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.scrapDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="台账保留期限" align="center" prop="keepPeriod" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equ:scrap:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equ:scrap:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 新增/修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="formRef" :model="formModel" :rules="rules" label-width="120px" class="view-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="报废申请id" prop="scrapId">
              <el-input v-model="formModel.scrapId" placeholder="请输入报废申请id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产设备id" prop="assetId">
              <el-input v-model="formModel.assetId" />
            </el-form-item>
          </el-col>

          <!-- JSON编辑器区域 -->
          <el-col :span="24">
            <el-form-item label="报废依据" prop="scrapBasis">
              <vue-json-editor
                v-model="formModel.scrapBasis"
                :options="jsonEditorOptions"
                class="json-editor clean-json-editor"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="审核汇总" prop="approvalSummary">
              <vue-json-editor
                v-model="formModel.approvalSummary"
                :options="jsonEditorOptions"
                class="json-editor clean-json-editor"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="处置信息" prop="disposalInfo">
              <vue-json-editor
                v-model="formModel.disposalInfo"
                :options="jsonEditorOptions"
                class="json-editor clean-json-editor"
              />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="正式报废日期" prop="scrapDate">
              <el-date-picker clearable
                              v-model="formModel.scrapDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择正式报废日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="台账保留期限" prop="keepPeriod">
              <el-input v-model="formModel.keepPeriod" placeholder="请输入台账保留期限" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="附件上传" prop="fileUrls">
              <file-upload v-model="formModel.fileUrls"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="formModel.remark" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VueJsonEditor from 'vue-json-editor';
import { listScrapVo, getScrap, delScrap, addScrap, updateScrap } from "@/api/equ/scrap";
import { getAllAssetName } from "@/api/equ/asset";

export default {
  name: "Scrap",
  components: { VueJsonEditor },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      scrapList: [],
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetName: null,
        timeRange: null,
      },
      formModel: {
        scrapId: null,
        assetId: null,
        scrapDate: null,
        keepPeriod: null,
        remark: null,
        scrapBasis: {},
        approvalSummary: {},
        disposalInfo: {},
        fileUrls: {}
      },
      uniqueAssetNames: [],
      rules: {
        scrapId: [
          { required: true, message: "报废申请id不能为空", trigger: "blur" }
        ],
        assetId: [
          { required: true, message: "资产设备id不为空", trigger: "blur" }
        ]
      },
      jsonEditorOptions: {
        mode: 'form',
        expanded: true,
        showBtn: false,
        indentation: 2,
        mainMenuBar: false
      }
    };
  },
  created() {
    this.getList();
    this.getAllAssetName();
  },
  methods: {
    getList() {
      this.loading = true;
      const [startTime, endTime] = this.queryParams.timeRange || [];
      const params = {
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        ...(this.queryParams.assetName && { assetName: this.queryParams.assetName }),
        ...(startTime && { startTime }),
        ...(endTime && { endTime })
      };
      listScrapVo(params).then(response => {
        this.scrapList = response.rows;
        this.total = response.total;
      }).catch(error => {
        console.error('查询报废列表失败：', error);
      }).finally(() => {
        this.loading = false;
      });
    },

    getAllAssetName() {
      getAllAssetName().then(response => {
        const data = response.data || [];
        this.uniqueAssetNames = data.map(item =>
          typeof item === 'object' ? item.assetName : item
        ).filter(Boolean);
      }).catch(error => {
        console.error('获取资产名称失败：', error);
        this.$modal.msgError('获取资产名称失败，请刷新重试');
      });
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.formModel = {
        scrapId: null,
        assetId: null,
        scrapDate: null,
        keepPeriod: null,
        remark: null,
        scrapBasis: {},
        approvalSummary: {},
        disposalInfo: {},
        fileUrls: {}
      };
      this.$refs.formRef?.clearValidate();
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.scrapId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报废记录";
    },

    handleUpdate(row) {
      this.reset();
      getScrap(row.scrapId).then(response => {
        const data = response.data;
        this.formModel = {
          ...data,
          scrapBasis: this.safeParseJSON(data.scrapBasis),
          approvalSummary: this.safeParseJSON(data.approvalSummary),
          disposalInfo: this.safeParseJSON(data.disposalInfo),
          fileUrls: this.safeParseJSON(data.fileUrls) || {}
        };
        this.open = true;
        this.title = "修改报废记录";
      }).catch(error => {
        console.error('获取报废详情失败：', error);
        this.$modal.msgError('获取详情失败，请重试');
      });
    },

    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          // 处理附件URL格式
          const formattedFileUrls = {};
          if (this.formModel.fileUrls && typeof this.formModel.fileUrls === 'object') {
            Object.entries(this.formModel.fileUrls).forEach(([key, relativeUrls]) => {
              if (Array.isArray(relativeUrls)) {
                formattedFileUrls[key] = relativeUrls.map(url =>
                  url.startsWith('http') ? url : `${process.env.VUE_APP_BASE_API}${url}`
                );
              }
            });
          }

          const submitData = {
            ...this.formModel,
            scrapBasis: JSON.stringify(this.formModel.scrapBasis || {}),
            approvalSummary: JSON.stringify(this.formModel.approvalSummary || {}),
            disposalInfo: JSON.stringify(this.formModel.disposalInfo || {}),
            fileUrls: JSON.stringify(formattedFileUrls || {})
          };

          const request = submitData.scrapId ? updateScrap : addScrap;
          request(submitData).then(() => {
            this.open = false;
            this.$modal.msgSuccess(submitData.scrapId ? "修改成功" : "新增成功");
            this.getList();
          }).catch(error => {
            console.error('提交失败：', error);
            this.$modal.msgError('操作失败，请重试');
          });
        }
      });
    },

    handleDelete(row) {
      const scrapIds = row ? [row.scrapId] : this.ids;
      this.$modal.confirm(`确定要删除选中的 ${scrapIds.length} 条记录吗？`).then(() => {
        return delScrap(scrapIds);
      }).then(() => {
        this.$modal.msgSuccess("删除成功");
        this.getList();
      }).catch(() => {});
    },

    handleExport() {
      this.download('equ/scrap/export', {
        ...this.queryParams
      }, `scrap_${new Date().getTime()}.xlsx`);
    },

    safeParseJSON(jsonString) {
      if (!jsonString || typeof jsonString !== 'string') {
        return {};
      }
      try {
        return JSON.parse(jsonString);
      } catch (e) {
        console.error('JSON解析失败：', e, '原始字符串：', jsonString);
        this.$modal.msgError('数据解析失败，请联系管理员');
        return {};
      }
    }
  }
};
</script>

<style scoped>
.view-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}

.view-form::-webkit-scrollbar {
  width: 8px;
}
.view-form::-webkit-scrollbar-track {
  background: #f1f1f1;
}
.view-form::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}
.view-form::-webkit-scrollbar-thumb:hover {
  background: #909399;
}

.json-editor {
  min-height: 200px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.clean-json-editor >>> .jsoneditor-menu,
.clean-json-editor >>> .jsoneditor-search,
.clean-json-editor >>> .jsoneditor-dragarea {
  display: none !important;
}
</style>
